<template>
	<div class="about">
		<h1>{{id ? '编辑' : '新建'}}物品</h1>
		<el-form label-width="120px" v-on:submit.native.prevent="save">
			<el-form-item label="名称">
        <el-input v-model="model.name">
				</el-input>
      </el-form-item>
			<el-form-item label="图标">
				<!-- 看elemen-ui中的上传upload -->
				<!-- actions那里不是用axios请求，所以路径要写全（绝对路径），不建议写http://localhost:3000/admin/api，后面修改路径会很麻烦 -->
				<!-- 成功以后添加时间afterUpload -->
				<el-upload
					class="avatar-uploader"			
					:action="uploadUrl"	
					:headers="getAuthHeaders()"		
					:show-file-list="false"
					:on-success="afterUpload"
        >
					<img v-if="model.icon" :src="model.icon" class="avatar">
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
			<el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
		</el-form>
	</div>
</template>

<script>
/* eslint-disable */
export default {
	data(){
		return {
			model:{},
		}
	},
	// 接收id，尽可能与路由解耦
	props:{
		id: {}
	},
	methods:{
		async afterUpload(res){
			// this.model.icon = res.url
			// vue的一个强制赋值的方法，因为进入页面并没图片上传。model.icon == undefined，即使上传图片也不能显示
			this.$set(this.model, 'icon', res.url)
		},
		async save(){
			// console.log(this.id)
      let res
      if (this.id) {
        res = await this.$http.put(`rest/items/${this.id}`, this.model)
      } else {
        res = await this.$http.post('rest/items', this.model)
			}
			// const res = await this.$http.post('items', this.model)
			// push要加/ 斜杠，
			this.$router.push('/items/list')
			this.$message({
        type: 'success',
        message: '保存成功'
      })
		},
		async fetch(){
      const res = await this.$http.get(`rest/items/${this.id}`)
      this.model = res.data
		},
	},
	created(){
		// 存在id的情况下才执行fetch事件（编辑）
    this.id && this.fetch()
  }
}
</script>


